﻿using MongoDB.Driver;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using Sustainalytics.ClientDW.Entities.Universes;
using Sustainalytics.Entities;
using System;
using System.Configuration.Abstractions;
using System.Threading.Tasks;

namespace Sustainalytics.ScreeningTool.Synchronization.Caches
{
    public class TearSheetCompanyIdsCache : HashSetCache<Guid>
    {
    }

    public class TearSheetCompanyIdsCacheLoader : ICacheLoader<TearSheetCompanyIdsCache>
    {
        private readonly TearSheetCompanyIdsCache _cache;
        private readonly IMongoCollection<Account> _accountCollection;
        private readonly IMongoCollection<Universe> _universeCollection;
        private readonly IMongoCollection<UniverseCompany> _universeCompanyCollection;
        private readonly IAppSettings _appSettings;

        public TearSheetCompanyIdsCacheLoader(
            TearSheetCompanyIdsCache cache,
            IMongoCollection<Account> accountCollection,
            IMongoCollection<Universe> universeCollection,
            IMongoCollection<UniverseCompany> universeCompanyCollection,
            IAppSettings appSettings)
        {
            _cache = cache;
            _accountCollection = accountCollection;
            _universeCollection = universeCollection;
            _universeCompanyCollection = universeCompanyCollection;
            _appSettings = appSettings;
        }

        // Logic from TearSheetReportDataProvider.GetAccountCompanyIds()
        public async Task LoadAsync(ClientFacingProduct clientFacingProduct)
        {
            var accountName = _appSettings.AppSetting<string>("TearSheetAccountName");

            var accountId = await _accountCollection
                .Find(a => a.Name == accountName)
                .Project(a => a.Id)
                .SingleOrDefaultAsync();

            var universeId = await _universeCollection
                .Find(u => u.AccountId == accountId && u.Name == "ESG Research")
                .Project(u => u.Id)
                .SingleOrDefaultAsync();

            var ids = await _universeCompanyCollection
                .Find(uc => uc.AccountId == accountId && uc.UniverseId == universeId)
                .Project(uc => uc.CompanyId)
                .ToListAsync();

            _cache.AddItems(ids);
        }
    }
}
